/**
 * 
 */
package edu.byu.nlp.pipes;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.logging.Logger;

import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.io.Files;

public class FilenameToContents implements Function<Instance<String, String>, Instance<String, String>> {

	public static Logger logger = Logger.getLogger(FilenameToContents.class.getName());
	
	private final File basedir;
	private final Charset charset;
	
	public FilenameToContents() {
		this(new File("."));
	}
	
	public FilenameToContents(File basedir) {
		this(basedir, Charset.defaultCharset());
	}
	
	public FilenameToContents(File basedir, Charset charset) {
		Preconditions.checkNotNull(charset);
		
		this.basedir = basedir;
		this.charset = charset;
	}

	/** {@inheritDoc} */
	@Override
	public Instance<String, String> apply(Instance<String, String> instance) {
		try {
			String filename = instance.getData(); 
			logger.fine("Processing " + filename);
			return new BasicInstance<String, String>(
					instance.getLabel(),
					new File(basedir, filename).toString(),
					Files.toString(new File(basedir, filename), charset));
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

}
